
import 'dart:async';

// import 'package:autophone/autophone.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:massagist/manager/config.dart';
import 'package:massagist/pages/phone_auto_page.dart';
import 'package:massagist/pages/privacy_page.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:talkingdata/talkingdata.dart';
// import 'package:talkingdata_sdk_plugin/talkingdata_sdk_plugin.dart';

import '../generated/l10n.dart';
import '../manager/request.dart';

class SplashPage extends StatefulWidget {
  @override
  State<SplashPage> createState() => SplashPageState();
}

class SplashPageState extends State<SplashPage> {
  final talkingPlugin = Talkingdata();
  // final autoPlugin = Autophone();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    
    // TalkingDataSDK.init(appID: "7CA922EB209D4E3D8023C69353EBC14A", channelID: "AppStore");
    // initTimer();

    requestTime();
  }

  Future<void> requestTime() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool result = prefs.getBool("is_first")?? true;

    print (result.toString());
    if (result) {
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(builder: (context) => PrivacyPage()),
            (route) => false,
      );
    } else {
      requestPermission();
    }
  }

  void initTimer() {
    int counter = 0;
    Timer timer;
    timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      counter++;
      if (counter == 2) {
        timer.cancel();

        Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(builder: (context) => PhoneAutoPage()),
              (route) => false,
        );
      }
    });
  }

  Future<bool> requestLocation() async {
    Position position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high,
    );

    Config.lat = position.latitude;
    Config.lon = position.longitude;

    return true;
  }


  Future<void> requestPermission() async {
    [
      Permission.appTrackingTransparency,
      Permission.location
    ].request().then((value)  async {
      print (value.toString());
      bool result = await requestInfo();
      print ("信息 = " + result.toString());
      // result = await requestLocation();
      // print ("位置 = " + result.toString());
      // String auto = await autoPlugin.phoneAuto();
      // print ("结果 = " + auto);

      Config.settingInfo = (await Request.requestSetting()).data;
      initTimer();

      // initPlatformState();
    });
  }

  Future<bool> requestInfo() async {
    Request.deviceinfo.initDeviceInfo();
    Request.ndgd = (await talkingPlugin.initTalkingData())!;
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        child: Column(
          // mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(top: 175.sp),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(50.sp),
                child: Image.network(
                  "https://img0.baidu.com/it/u=3575652686,492296591&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
                  width: 75.sp,
                  height: 75.sp,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 28.sp),
              child: Text(S.current.SPLASH_TITLE, style: const TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 15,
              )),
            )
          ],
        ),
      ),
    );
  }
}